<template>
  <div class="panel">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useResizeObserver } from '@vueuse/core'

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

// 模拟数据
const traceData = [
  { name: '大豆', value: 1250 },
  { name: '玉米', value: 980 },
  { name: '小麦', value: 1560 },
  { name: '水稻', value: 870 },
  { name: '其他', value: 1120 }
]

const initChart = () => {
  if (!chartRef.value) return

  chart = echarts.init(chartRef.value)

  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 次'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: traceData.map(item => item.name),
      axisLine: {
        lineStyle: {
          color: '#33ffd0'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#33ffd0'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(51, 255, 208, 0.1)'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 12
      }
    },
    series: [
      {
        name: '追溯次数',
        type: 'bar',
        data: traceData.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#33ffd0' },
            { offset: 1, color: 'rgba(51, 255, 208, 0.3)' }
          ])
        },
        barWidth: '40%',
        label: {
          show: true,
          position: 'top',
          color: '#33ffd0',
          fontSize: 12
        }
      }
    ]
  }

  chart.setOption(option)
}

// 监听容器大小变化
useResizeObserver(chartRef, () => {
  chart?.resize()
})

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  chart?.dispose()
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
